package cn.fz.mpdemo.service.impl;

import cn.fz.mpdemo.dao.EmpMapper;
import cn.fz.mpdemo.domain.po.DeptEntity;
import cn.fz.mpdemo.domain.po.EmpEntity;
import cn.fz.mpdemo.domain.query.EmpQuery;
import cn.fz.mpdemo.domain.request.EmpRequest;
import cn.fz.mpdemo.domain.vo.PageVO;
import cn.fz.mpdemo.exception.BizException;
import cn.fz.mpdemo.service.DeptService;
import cn.fz.mpdemo.service.EmpService;
import cn.fz.mpdemo.utils.ImportExcelUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 员工表 服务实现类
 * </p>
 *
 * @author gecy
 * @since 2024-07-06 14:24:14
 */
@Service
@RequiredArgsConstructor
public class EmpServiceImpl extends ServiceImpl<EmpMapper, EmpEntity> implements EmpService {
    private final DeptService deptService;

    @Override
    public EmpEntity login(String username, String password) {
        EmpEntity emp = lambdaQuery().eq(EmpEntity::getUsername, username).one();
        if (ObjUtil.isEmpty(emp)) {
            throw new BizException(username + "不存在");
        }
        // 判断密码是否相等
        String curPwd = SecureUtil.md5(password + emp.getSalt()).toLowerCase();
        if (!curPwd.equals(emp.getPassword())) {
            throw new BizException(password + "密码错误");
        }
        return emp;
    }

    @Override
    public PageVO<EmpEntity> queryPage(EmpQuery query) {
        Page<EmpEntity> p = query.toMpPage("id", false);
        QueryWrapper<EmpEntity> wrapper = getEmpEntityQueryWrapper(query);
        this.page(p, wrapper);
        if (p.getTotal() <= 0) {
            return new PageVO<>(0L, 0L, Collections.emptyList());
        }
        return new PageVO<>(p.getTotal(), p.getPages(), p.getRecords());
    }

    private static QueryWrapper<EmpEntity> getEmpEntityQueryWrapper(EmpQuery query) {
        QueryWrapper<EmpEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .like(StrUtil.isNotEmpty(query.getName()), EmpEntity::getName, query.getName())
                .like(StrUtil.isNotEmpty(query.getUsername()),EmpEntity::getUsername, query.getUsername());
        return wrapper;
    }

    @Override
    public List<Map<String, String>> readExcelFile(MultipartFile file) {
        try (ExcelReader reader = ExcelUtil.getReader(file.getInputStream())) {
            List<Sheet> sheets = reader.getSheets();
            Sheet rows = sheets.get(0);
            return ImportExcelUtil.getSheetData(rows);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public void export(EmpQuery query, HttpServletResponse response) {
        Wrapper<EmpEntity> wrapper = getEmpEntityQueryWrapper(query);
        List<EmpEntity> list = list(wrapper);
        try(ExcelWriter writer = ExcelUtil.getWriter()){
            writer.write(list,true);
            String fileName = "diaomao";
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            try (ServletOutputStream sos = response.getOutputStream()){
                writer.flush(sos,true);
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Transactional
    @Override
    public void saveEmp(EmpRequest request) {
        DeptEntity build = DeptEntity.builder().name(request.getDeptName()).createTime(LocalDateTime.now()).build();
        deptService.save(build);
        System.out.println(build);
        // int x = 1 / 0;
        String salt = RandomUtil.randomString(8);
        String password = SecureUtil.md5(request.getPassword() + salt);
        EmpEntity emp = EmpEntity.builder()
                .deptId(build.getId())
                .username(request.getUsername())
                .password(password)
                .salt(salt)
                .gender(request.getGender())
                .name(request.getName())
                .job(request.getJob())
                .createTime(LocalDateTime.now())
                .build();
        this.save(emp);
    }
}
